<?php

ob_start("ob_gzhandler");
if (!isset($_SESSION)) {
    session_start();
}
require('../../Smarty/libs/Smarty.class.php');
include_once 'API/APIObject.php';
include_once 'API/Utils.php';
$smarty = new Smarty;

$smarty->setTemplateDir('./smarty/templates/');
$smarty->setCompileDir('./smarty/templates_c/');
$smarty->setConfigDir('./smarty/configs/');
$smarty->setCacheDir('./smarty/cache/');
$smarty->setCaching(true);      // activating caching of the pages
$smarty->force_compile = true;  // forcing compiling the templates for ajax

$continue = true;
$amenities = array();
$hotelArray = array();
$output = "";

// POST DATA
if (isset($_POST)) {
    if (isset($_POST["hotelId"]) && $continue == true) {
        $hotelId = $_POST["hotelId"];
    } else {
        $continue = false;
    }
    if (isset($_POST["service"]) && $continue == true) {
        $service = $_POST["service"];
    } else {
        $continue = false;
    }
    if (isset($_POST["rateCode"])) {
        $rateCode = $_POST["rateCode"];
    }
    if (isset($_POST["roomTypeCode"])) {
        $roomTypeCode = $_POST["roomTypeCode"];
    }
    if (isset($_POST["rateKey"]) && $continue == true) {
        $rateKey = $_POST["rateKey"];
    }
    if (isset($_POST["thumbnailImage"]) && $continue == true) {
        $hotelImage = $_POST["thumbnailImage"];
    }
}
if (isset($_SESSION)) {
    if (isset($_SESSION["search"]["checkIn"])) {
        $checkIn = $_SESSION["search"]["checkIn"];
    } else {
        $continue = FALSE;
    }
    if (isset($_SESSION["search"]["checkOut"])) {
        $checkOut = $_SESSION["search"]["checkOut"];
    } else {
        $continue = FALSE;
    }
    if (isset($_SESSION["search"]["roomCount"])) {
        $roomCount = $_SESSION["search"]["roomCount"];
    } else {
        $continue = FALSE;
    }
    if (isset($_SESSION["rooms"])) {
        $roomsData = $_SESSION["rooms"];
    }
} else {
    $continue = FALSE;
}

$api = new APIObject();
$filter = new Filter();

$smarty->assign("server", 'bookingPage.php');
$filter->supplierType = "E";
$filter->RoomGroup = new RoomGroup(NULL, 1);

for ($i = 1; $i <= $roomCount; $i++) {
    $filter->RoomGroup->Room[$i] = new Room();
    $filter->RoomGroup->Room[$i]->numberOfAdults = $roomsData[$i]['adults'];
    $splitResult = explode(",", $roomsData[$i]['ages_string']);
    for ($j = 0; $j < $roomsData[$i]['children']; $j++) {
        $filter->RoomGroup->Room[$i]->childAges = ($splitResult) ? $splitResult[$j] : "";
    }
}

// HARDCODED DATA FOR HOTEL INFORMATION
$options = "HOTEL_SUMMARY,HOTEL_DETAILS,PROPERTY_AMENITIES";

// HARDCODED DATA FOR ROOM AVAILABILITY
$numberOfBedRooms = NULL;
$supplierType = "E";

if (!isset($rateKey)) {
    $rateKey = NULL;
}
if (!isset($roomTypeCode) || !isset($rateCode)) {
    $roomTypeCode = NULL;
    $rateCode = NULL;
}
$includeDetails = FALSE;
$includeRoomImages = FALSE;
$optionsAvail = "ROOM_TYPES";
$roomGroup = $filter->RoomGroup;


if ($service == "INFO") {
// HOTEL INFORMATION CALL
    $hotelResponse = $api->GetHotelInformation($hotelId, $options);
    $hotelSummary = $hotelResponse->HotelSummary;
    $hotelDetails = $hotelResponse->HotelDetails;
    $propertyAmenities = $hotelResponse->PropertyAmenities;
    $index = 1;
    foreach ($propertyAmenities->PropertyAmenity as $value) {
        $amenities[$index]["amenity"] = $value->amenity;
        $amenities[$index++]["amenityId"] = $value->amenityId;
    }
    $hotelArray = array(
        "hotelPolicy" => $hotelDetails->hotelPolicy,
        "checkInInstructions" => $hotelDetails->checkInInstructions,
        "roomInformation" => $hotelDetails->roomInformation,
        "propertyDescription" => html_entity_decode($hotelDetails->propertyDescription),
        "areaInformation" => $hotelDetails->areaInformation,
        "checkInTime" => $hotelDetails->checkInTime,
        "checkOutTime" => $hotelDetails->checkOutTime,
        "id" => $hotelSummary->hotelId,
        "hotelName" => $hotelSummary->name,
        "supplierType" => "E",
        "propertyAmenities" => $amenities,
        "propertyCategory" => $hotelSummary->propertyCategory
    );
    $smarty->assign("hotel", $hotelArray);
    $output = $smarty->fetch('hotel_details.tpl');
} elseif ($service == "AVAIL") {
    // ROOM AVAILABILITTY CALL
    $roomAvail = $api->GetRoomAvailability(
            $hotelId, $checkIn, $checkOut, $numberOfBedRooms, $supplierType, $rateKey, $rateCode, $roomTypeCode, $includeDetails, $includeRoomImages, $optionsAvail, $roomGroup);
    if (is_array($roomAvail->HotelRoomResponse)) {
        $hotelRoomsRes = $roomAvail->HotelRoomResponse;
    } else {
        $hotelRoomsRes = array($roomAvail->HotelRoomResponse);
    }
    $positions = array();
    $cur = 0;
    foreach ($hotelRoomsRes as $index => $value) {
        $nightRates = 0;

        $rateInfo = isset($value->RateInfos->RateInfo) ? $value->RateInfos->RateInfo : "";

        if ($rateInfo != "") {
            if (is_array($rateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate)) {
                $nightlyRate = $rateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate;
            } else {
                $nightlyRate = array($rateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate);
            }
            foreach ($nightlyRate as $rate) {
                $nightRates += $rate->{"@rate"};
            }
        }

        $hotelRooms[$index] = array(
            "rateCode" => isset($value->rateCode) ? $value->rateCode : "",
            "roomTypeCode" => isset($value->RoomType->{"@roomCode"}) ? $value->RoomType->{"@roomCode"} : "",
            "roomTypeDescription" => isset($value->RoomType->descriptionLong) ? $value->RoomType->descriptionLong : "",
            "roomTypeString" => isset($value->RoomType->description) ? $value->RoomType->description : "",
            "minGuestAge" => isset($value->minGuestAge) ? $value->minGuestAge : "",
            "nonRefundable" => isset($value->nonRefundable) ? $value->nonRefundable : "",
            "promoId" => isset($value->promoId) ? $value->promoId : "",
            "promoDescription" => isset($value->promoDescription) ? $value->promoDescription : "",
            "currentAllotment" => isset($value->currentAllotment) ? $value->currentAllotment : "",
            "rateInfo" => array(
                "averageRate" => isset($rateInfo->ChargeableRateInfo->{"@averageRate"}) ? $rateInfo->ChargeableRateInfo->{"@averageRate"} : "",
                "total" => isset($rateInfo->ChargeableRateInfo->{"@total"}) ? $rateInfo->ChargeableRateInfo->{"@total"} : "",
                "currencyCode" => isset($rateInfo->ChargeableRateInfo->{"@currencyCode"}) ? $rateInfo->ChargeableRateInfo->{"@currencyCode"} : "",
                "surchargeTotal" => isset($rateInfo->ChargeableRateInfo->{"@surchargeTotal"}) ? $rateInfo->ChargeableRateInfo->{"@surchargeTotal"} : "",
                "nightlyRatesTotal" => isset($nightRates) ? $nightRates : "",
                "salesTax" => "",
                "hotelOccupancyTax" => ""
            ),
            "noData" => ($rateInfo == "") ? true : false
        );
    }

    $hotelArray = array(
        "rateKey" => isset($roomAvail->rateKey) ? $roomAvail->rateKey : "",
        "id" => isset($roomAvail->hotelId) ? $roomAvail->hotelId : "",
        "checkInInstructions" => isset($roomAvail->checkInInstructions) ? $roomAvail->checkInInstructions : "",
        "supplierType" => "E",
        "checkin" => $checkIn,
        "checkout" => $checkOut,
        "thumbnailUrl" => $hotelImage,
        "hotelName" => $roomAvail->hotelName,
        "room" => $hotelRooms
    );

    $smarty->assign("hotel", $hotelArray);
    $output = $smarty->fetch('room_details.tpl');
} elseif ($service == "CANCEL") {
    $rateKey = $_POST["rateKey"];
    $rateCode = $_POST["rateCode"];
    $roomTypeCode = $_POST["roomTypeCode"];
    $roomAvail = $api->GetRoomAvailability(
            $hotelId, $checkIn, $checkOut, $numberOfBedRooms, $supplierType, $rateKey, $rateCode, $roomTypeCode, $includeDetails, $includeRoomImages, $optionsAvail, $roomGroup);
    try {
        $cancellationPolicy = isset($roomAvail->HotelRoomResponse->cancellationPolicy) ? $roomAvail->HotelRoomResponse->cancellationPolicy : "Cancellation policy was not found ! Please do not book this room. If you try to book the room, you are doing it on your own risk.";
        $smokingPreferences = isset($roomAvail->HotelRoomResponse->smokingPreferences) ? $roomAvail->HotelRoomResponse->smokingPreferences : "";
        $smarty->assign("cancellationPolicy", $cancellationPolicy);
        $smarty->assign("smokingPreferences", $smokingPreferences);
        $_SESSION["cancellationPolicy"] = $cancellationPolicy;
        $_SESSION["smokingPreferences"] = $smokingPreferences;
        $_SESSION["averageRate"] = isset($roomAvail->HotelRoomResponse->RateInfos->RateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate->{"@rate"}) ? $roomAvail->HotelRoomResponse->RateInfos->RateInfo->ChargeableRateInfo->NightlyRatesPerRoom->NightlyRate->{"@rate"} : "Not Available";
        //var_dump($roomAvail);

        $smarty->assign("id", $hotelId);
        $smarty->assign("roomTypeCode", $roomTypeCode);
        $output = $smarty->fetch('cancelation_policy.tpl');
    } catch (Exception $exp) {
        $output = "";
    }
} elseif ($service == "IMG") {
    // HOTEL INFORMATION CALL
    // HARDCODED DATA FOR HOTEL INFORMATION

    $options = "HOTEL_IMAGES";
    $hotelArray = array();
    $hotelResponse = $api->GetHotelInformation($hotelId, $options);
    $hotelImages = $hotelResponse->HotelImages->HotelImage;
    $imageCount = count($hotelImages);
    if ($imageCount == 1) {
        $hotelImages = array($hotelResponse->HotelImages->HotelImage);
    }
    foreach ($hotelImages as $key => $value) {
        $hotelArray[$key] = array(
            /* "caption" => $value->caption, */
            "thumbnailUrl" => substr_replace($value->thumbnailUrl, "t", -5, 1),
            "url" => $value->url /* substr_replace($value->url,"y",-5,1) */,
            "id" => $hotelId,
            "nr_picture" => $key,
            "caption" => ""
        );
    }
    $smarty->assign("imageCount", $imageCount);
    $smarty->assign("hotelId", $hotelId);
    $smarty->assign("hotel", $hotelArray);
    $output = $smarty->fetch('hotel_gallery.tpl');
}

print_r($output);
?>